package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.OrderSourceEnum;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.XlslUtil;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.uuid.OrderNumberGenerator;
import com.ruoyi.system.domain.dto.XsOrderDto;
import com.ruoyi.system.domain.dto.XsOrderImportDto;
import com.ruoyi.system.domain.vo.XsStatisticsVo;
import com.ruoyi.system.domain.vo.order.XsOrderListVo;
import com.ruoyi.system.domain.vo.order.XsOrderVo;
import com.ruoyi.system.domain.xs.XsOrder;
import com.ruoyi.system.domain.xs.XsOrderTb;
import com.ruoyi.system.mapper.XsOrderMapper;
import com.ruoyi.system.service.IXsOrderService;
import com.ruoyi.system.service.IXsOrderTbService;
import com.ruoyi.system.service.IXsStoreService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class XsOrderServiceImpl extends ServiceImpl<XsOrderMapper, XsOrder>
        implements IXsOrderService {

    private final IXsStoreService xsStoreService;

    private final XsOrderMapper xsOrderMapper;

    private final IXsOrderTbService xsOrderTbService;

    private final ScheduledThreadPoolExecutor scheduledExecutor = ThreadUtil.createScheduledExecutor(1);

    /**
     * 查询订单列表
     *
     * @param orderDto
     * @return
     */
    @Override
    public List<XsOrderListVo> selectOrderList(XsOrderDto orderDto) {
        //状态流转
        stateFlow();
        orderDto.setPerformance(orderDto.getSettlementDate());
        SysUser user = SecurityUtils.getLoginUser().getUser();
        List<SysRole> roles = user.getRoles();
        Boolean ifAdmin=false;
        for (SysRole role : roles) {
            if (role.getRoleName().equals("超级管理员")||role.getRoleName().equals("平台管理员")){
                ifAdmin=true;
            }
        }
        if (!ifAdmin){
            orderDto.setCreateBy(user.getUserId().toString());
        }

        List<XsOrderListVo> vo = xsOrderMapper.queryOrderList(orderDto);
//        if (CollectionUtil.isNotEmpty(vo)) {
//            for (XsOrderListVo orderListVo : vo) {
//                boolean b = StringUtils.isNotEmpty(orderListVo.getWriterNickName())
//                        && StringUtils.isNotEmpty(orderListVo.getServiceCode());
//                orderListVo.setCheckSheet( b ? orderListVo.getCheckSheet() : "4");
//                orderListVo.setIfBalance(b ? orderListVo.getIfBalance() : "2");
//                boolean c = ("4".equals(orderListVo.getStatus()) && orderListVo.getPutPayment().compareTo(BigDecimal.ZERO) == 0)
//                        || ("2".equals(orderListVo.getStatus())
//                        && ("0".equals(orderListVo.getAfterRefund())
//                        || new BigDecimal(orderListVo.getAfterRefund()).compareTo(orderListVo.getActualPayment()) < 0))
//                        || ("1".equals(orderListVo.getStatus()) && new BigDecimal(orderListVo.getRefund()).compareTo(orderListVo.getActualPayment()) < 0);
//                 orderListVo.setCheckSheet(c ? "1" : orderListVo.getCheckSheet());
//            }
//        }
        return vo;
    }

    /**
     * 新增加
     *
     * @param orderDto
     * @return
     */
    @Override
    @Transactional
    public boolean add(XsOrderDto orderDto) {
        return true;
    }

    /**
     * 删除
     *
     * @param ids
     * @return
     */
    @Override
    public boolean deleteXsOrderByIds(Long[] ids) {
        List<Long> idList = Arrays.stream(ids).collect(Collectors.toList());
        return this.removeBatchByIds(idList);
    }

    @Override
    public XsOrderVo orderDetails(String orderId) {
        XsOrderVo vo = new XsOrderVo();
        XsOrder xsOrder = lambdaQuery().eq(XsOrder::getOrderId, orderId).last("limit 1").one();
        BeanUtil.copyProperties(xsOrder, vo);
        if (ObjectUtil.isEmpty(xsOrder)) {
            XsOrderTb tb = xsOrderTbService.lambdaQuery().eq(XsOrderTb::getOrderId, orderId).last("limit 1").one();
            if (ObjectUtil.isNotEmpty(tb)) {
                tb.setCheckSheet(StringUtils.isEmpty(tb.getCheckSheet()) ? "2" : tb.getCheckSheet());
                BeanUtil.copyProperties(tb, vo);
            }
        }
        return vo;
    }

    /**
     * 获得统计数据
     *
     * @param orderDto
     * @return
     */
    @Override
    public XsStatisticsVo getOrderStatistics(XsOrderDto orderDto) {
//        return xsOrderMapper.statistics(orderDto);
        if (StringUtils.isNotEmpty(orderDto.getOrderIdStr()))
            orderDto.setOrderIdList(Arrays.asList(orderDto.getOrderIdStr().split(",")));
        return xsOrderMapper.newStatistics(orderDto);
    }

    @Override
    public boolean updateBdmUser(XsOrderDto orderDto) {
        XsOrder order = new XsOrder();
        BeanUtil.copyProperties(orderDto, order);
        order.setWriterPaidPrice(StringUtils.isNotEmpty(orderDto.getWriterPaidPrice()) ? orderDto.getWriterPaidPrice() : "0");
        order.setUpdateBy(SecurityUtils.getUsername());
        order.setUpdateTime(DateUtils.getNowDate());
        order.setModified(DateUtils.getNowDate());
        //如果结算是 客服加写手 则修改为已结算
        if (StringUtils.isNotEmpty(orderDto.getSettle())&&orderDto.getSettle().indexOf(",")>0){
            order.setIfBalance("1");
            xsOrderTbService.lambdaUpdate().eq(XsOrderTb::getAcookieId,orderDto.getAcookieId()).set(XsOrderTb::getIfBalance,"1").update();
        }




        List<XsOrder> orderList = lambdaQuery().eq(XsOrder::getAcookieId, orderDto.getAcookieId()).list();
        if (CollectionUtil.isEmpty(orderList)) {
            order.setCreateTime(DateUtils.getNowDate());
            order.setCreateBy(SecurityUtils.getUsername());
            order.setModified(DateUtils.getNowDate());
            return this.save(order);
        } else {
            return this.lambdaUpdate().eq(XsOrder::getOrderId, orderDto.getOrderId()).update(order);
        }
    }

    @Override
    public boolean editNew(XsOrderDto xsOrderDto) {
     return this.updateById(BeanUtil.copyProperties(xsOrderDto,XsOrder.class));
    }

    /**
     * 修改是否刷单
     *
     * @param orderDto
     * @return
     */
    @Override
    @Transactional
    public boolean editBrushing(XsOrderDto orderDto) {
        boolean a = this.lambdaUpdate()
                .set(ObjectUtil.isNotEmpty(orderDto.getIfBrushing()), XsOrder::getIfBrushing, orderDto.getIfBrushing())
                .set(StringUtils.isNotEmpty(orderDto.getCheckSheet()), XsOrder::getCheckSheet, orderDto.getCheckSheet())
                .set(StringUtils.isNotEmpty(orderDto.getIfBalance()), XsOrder::getIfBalance, orderDto.getIfBalance())
                .set(StringUtils.isNotEmpty(orderDto.getIfBalance()) && "1".equals(orderDto.getIfBalance()), XsOrder::getSettlementDate, DateUtils.getNowDate())
                .set(StringUtils.isNotEmpty(orderDto.getIfAudit()), XsOrder::getIfAudit, orderDto.getIfAudit())
                .eq(StringUtils.isNotEmpty(orderDto.getAcookieId()) && !"线下订单".equals(orderDto.getAcookieId()), XsOrder::getAcookieId, orderDto.getAcookieId())
                .eq(StringUtils.isNotEmpty(orderDto.getOrderId()) && "线下订单".equals(orderDto.getAcookieId()), XsOrder::getOrderId, orderDto.getOrderId())
                .update();
        boolean b = true;
        if (StringUtils.isEmpty(orderDto.getIfAudit())) {
            b = xsOrderTbService.lambdaUpdate()
                    .set(ObjectUtil.isNotEmpty(orderDto.getIfBrushing()), XsOrderTb::getIfBrushing, orderDto.getIfBrushing())
                    .set(StringUtils.isNotEmpty(orderDto.getCheckSheet()), XsOrderTb::getCheckSheet, orderDto.getCheckSheet())
                    .set(StringUtils.isNotEmpty(orderDto.getIfBalance()), XsOrderTb::getIfBalance, orderDto.getIfBalance())
                    .set(StringUtils.isNotEmpty(orderDto.getIfBalance()) && "1".equals(orderDto.getIfBalance()), XsOrderTb::getSettlementDate, DateUtils.getNowDate())
                    .eq(XsOrderTb::getAcookieId, orderDto.getAcookieId())
                    .update();
        }
        if (StringUtils.isNotEmpty(orderDto.getCheckSheet()) && !"线下订单".equals(orderDto.getAcookieId())) {
            List<XsOrder> orderList = lambdaQuery().eq(XsOrder::getAcookieId, orderDto.getAcookieId()).list();
            if (CollectionUtil.isEmpty(orderList)) {
                List<XsOrderTb> tbList = xsOrderTbService.lambdaQuery().eq(XsOrderTb::getAcookieId, orderDto.getAcookieId()).list();
                List<XsOrder> orders = new ArrayList<>();
                if (CollectionUtil.isNotEmpty(tbList)) {
                    for (XsOrderTb orderTb : tbList) {
                        XsOrder order = new XsOrder();
                        BeanUtil.copyProperties(orderTb, order);
                        order.setId(null);
                        order.setCreateTime(DateUtils.getNowDate());
                        order.setCreateBy(SecurityUtils.getUsername());
                        order.setModified(DateUtils.getNowDate());
                        orders.add(order);
                    }
                }
                // 未找到 就插入
                return this.saveBatch(orders);
            }
        }
        return a || b;
    }

    //状态流转 修改到了 指定天数的 是否报账 和 是否结算
    @Override
    public void stateFlow() {
     xsOrderMapper.stateFlow();
     xsOrderMapper.stateFlow2();
    }

    @Override
    public AjaxResult batchImportClue(List<MultipartFile> file) {
        try {
            if (CollectionUtils.isEmpty(file)) {
                return AjaxResult.success("请上传文件");
            }
            List<XsOrder> xsOrders = new ArrayList<>();

            Map<String, String> map = new HashMap<>();
            xsStoreService.lambdaQuery().list().forEach(store -> {
                map.put(store.getStoreName(), store.getStoreCode());
            });


            for (MultipartFile item : file) {
                if (ObjectUtils.isEmpty(item)) {
                    continue;
                }
                Workbook workBook = XlslUtil.getWorkBook(item);
                if (ObjectUtils.isEmpty(workBook)){
                    continue;
                }
                for (int sheetNum = 0; sheetNum < workBook.getNumberOfSheets(); sheetNum++) {
                    Sheet sheet = workBook.getSheetAt(sheetNum);
                    if (ObjectUtils.isEmpty(sheet)) {
                        continue;
                    }
                    String sheetName = sheet.getSheetName();

                    Map<String, PictureData> sheetPictures = XlslUtil.getSheetPictures((XSSFSheet) sheet);
                    int lastRowNum = sheet.getLastRowNum();
                    for (int i = 1; i <= lastRowNum; i++) {
                        Row row = sheet.getRow(i);
                        if (ObjectUtils.isEmpty(row)) {
                            continue;
                        }
                        Cell cell1 = row.getCell(0);
                        if (ObjectUtils.isEmpty(cell1)) {
                            continue;
                        }
                        //设置单元格类型
                        cell1.setCellType(CellType.STRING);
                        //获取单元格数据
                        String cellValuet = cell1.getStringCellValue();
                        if (StringUtils.isEmpty(cellValuet)&&!(sheetPictures.containsKey(i+":"+0))){
                            continue;
                        }
                        XsOrder xsOrder = new XsOrder();
                        short lastCellNum = row.getLastCellNum();
                        for (int j = 0; j <= lastCellNum; j++) {
                            Cell cell = row.getCell(j);
                            if (ObjectUtils.isEmpty(cell)) {
                                continue;
                            }
                            //设置单元格类型
                            cell.setCellType(CellType.STRING);
                            //获取单元格数据
                            String cellValue = cell.getStringCellValue().trim();
                            if (StringUtils.isEmpty(cellValue)&&!(sheetPictures.containsKey(i+":"+j))){
                                continue;
                            }
                            //判断cell是否为图片 图片的话转换为二进制
                            switch (j) {
                                case 0:
                                    if (sheetPictures.containsKey(i + ":" + j)) {
                                        PictureData pictureData = sheetPictures.get(i + ":" + j);
                                        byte[] data = pictureData.getData();
                                        String s1 = XlslUtil.compressAndEncode(data);
                                        xsOrder.setPicOrDic(s1);
                                    } else {
                                        xsOrder.setAcookieId(cellValue);
                                    }
                                    xsOrder.setCreateBy(SecurityUtils.getUserId().toString());
                                    xsOrder.setCreateTime(DateUtils.getNowDate());
                                    if (StringUtils.isNotEmpty(map)) {
                                        Pattern pattern = Pattern.compile("笔|墨");
                                        Matcher matcher = pattern.matcher(sheetName);
                                        if (matcher.find()) {
                                            xsOrder.setStoreCode(map.get("笔墨画千秋"));
                                            xsOrder.setOrderId(OrderNumberGenerator.generateOrderNumber("BM"));
                                        } else {
                                            xsOrder.setStoreCode(map.get("回字格"));
                                            xsOrder.setOrderId(OrderNumberGenerator.generateOrderNumber("HZG"));
                                        }
                                    }

                                    break;
                                case 1:
                                    xsOrder.setBuyerOpenUid(cellValue);
                                    break;
                                case 2:
                                    xsOrder.setServiceCode(cellValue);
                                    break;
                                case 3:
                                    xsOrder.setOrderAcceptanceDate(DateUtils.parseDate(cellValue));
                                    break;
                                case 4:
                                    xsOrder.setTitle(cellValue);
                                    break;
                                case 5:
                                    if (XlslUtil.isNumericUsingRegex(cellValue)){
                                        xsOrder.setPutPayment(new BigDecimal(cellValue));
                                    }
                                    break;
                                case 6:
                                    xsOrder.setWriterNickName(cellValue);
                                    break;
                                case 7:
                                    if (XlslUtil.isNumericUsingRegex(cellValue)){
                                        xsOrder.setActualPayment(new BigDecimal(cellValue));
                                    }
                                    break;
                                case 8:
                                    xsOrder.setSellerMemo(cellValue);
                                    break;
                                case 9:
                                    xsOrder.setAccount(cellValue);
                                    break;
                                case 10:
                                    xsOrder.setWriterName(cellValue);
                                    break;
                                case 11:
                                    xsOrder.setCheckSheet(cellValue.equals("报") ? "1" : cellValue.equals("未报") ? "2" : cellValue.equals("重复报") ? "3" : "4");
                                    break;
                                case 12:
                                    xsOrder.setSettlementDate(DateUtils.parseDate(cellValue));
                                    break;
                                case 13:
                                    xsOrder.setSettlementRemark(cellValue);
                                    break;
                                case 14:
                                    if (cellValue.matches("\\d+")) {
                                        String s = XlslUtil.dateFmt(Long.parseLong(cellValue));
                                        xsOrder.setPerformance(s);
                                    }else {
                                        xsOrder.setPerformance(cellValue);
                                    }

                                    break;
                                case 15:
                                    xsOrder.setOrderSource(cellValue);
//                                cellValue.equals("淘宝") ? "1" : cellValue.equals("天猫") ? "2" : cellValue.equals("微信") ? "3"
//                                        : cellValue.equals("抖音") ? "4" : cellValue.equals("拼多多") ? "5" : cellValue.equals("对公") ? "6"
//                                        : cellValue.equals("线下") ? "7" : cellValue.equals("内部") ? "8" : "9"
                                    break;
                                case 16:
                                    xsOrder.setClientPaidPrice(cellValue);
                                    break;
                                case 17:
                                    xsOrder.setAdvanceAmount(cellValue);
                                    break;
                                case 18:
                                    xsOrder.setWriterPaidPrice(cellValue);
                                    break;
                                case 19:
                                    xsOrder.setStatus("交易关闭".equals(cellValue) ?"1"
                                            :"交易成功".equals(cellValue)?"2"
                                            :"买家已付款,等待卖家发货".equals(cellValue)?"3"
                                            :"卖家已发货，等待买家确认".equals(cellValue)?"4"
                                            :null);
                                    break;
                                case 20:
                                    xsOrder.setOfflineRefundAmount(new BigDecimal(cellValue));
                                    break;
                            }

                        }
                        xsOrders.add(xsOrder);
                    }
                }
            }

            scheduledExecutor.execute(()->{this.saveBatch(xsOrders);});

        }catch (IOException e){
            System.err.println(e.getMessage());
            throw new RuntimeException("数据格式错误请检查");
        }
        return AjaxResult.success();
    }


    /**
     * 批量修改补单
     * @param file
     * @return
     */
    @Override
    @Transactional
    public AjaxResult replenishment(List<MultipartFile> file) {
        if (CollectionUtils.isEmpty(file)) {
            return AjaxResult.success("请上传文件");
        }
        List<String> acookieIds = new ArrayList<>();
        for (MultipartFile item : file) {
            if (ObjectUtils.isEmpty(item)) {
                continue;
            }
            Workbook workBook = XlslUtil.getWorkBook(item);
            if (ObjectUtils.isEmpty(workBook)){
                continue;
            }
            for (int sheetNum = 0; sheetNum < workBook.getNumberOfSheets(); sheetNum++) {
                Sheet sheet = workBook.getSheetAt(sheetNum);
                if (ObjectUtils.isEmpty(sheet)) {
                    continue;
                }

                int lastRowNum = sheet.getLastRowNum();
                for (int i = 1; i <= lastRowNum; i++) {
                    Row row = sheet.getRow(i);
                    if (ObjectUtils.isEmpty(row)) {
                        continue;
                    }
                    Cell cell = row.getCell(0);
                    if (ObjectUtils.isEmpty(cell)){
                        continue;
                    }
                    cell.setCellType(CellType.STRING);
                    String stringCellValue = cell.getStringCellValue();
                    if (StringUtils.isEmpty(stringCellValue)){
                        continue;
                    }
                    acookieIds.add(stringCellValue);
                }
            }
        }
        //批量修改补单

        //千牛表
        xsOrderTbService.lambdaUpdate().set(XsOrderTb::getIfBrushing, 1)
                .in(XsOrderTb::getAcookieId, acookieIds).update();
        //客服表
        this.lambdaUpdate().set(XsOrder::getIfBrushing, 1)
                .in(XsOrder::getAcookieId, acookieIds).update();
        return AjaxResult.success();
    }

    /**
     * 批量修改结算
     * @param orderId
     * @return
     */
    @Override
    public AjaxResult expenseAccount(List<String> orderId) {

        xsOrderMapper.expenseAccount(orderId);
        xsOrderMapper.expenseAccount2(orderId);
//        //千牛表
//        xsOrderTbService.lambdaUpdate().set(XsOrderTb::getIfBalance, 1)
//                .in(XsOrderTb::getOrderId, orderId)
//                .update();
//        //客服表
//        this.lambdaUpdate().set(XsOrder::getIfBalance, 1)
//                .set(XsOrder::getSettle,"1,0")
//                .in(XsOrder::getOrderId, orderId).update();
        return AjaxResult.success();
    }

    @Transactional
    public boolean updateOrder(List<XsOrder> updateList) {
        if (StringUtils.isEmpty(updateList)) {
            return true;
        }
        return this.updateBatchById(updateList);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void batchImportDataClues(MultipartFile file) {
        ExcelUtil<XsOrderImportDto> util = new ExcelUtil<XsOrderImportDto>(XsOrderImportDto.class);
        int count = 2;

        String orderId = null;
        XSSFWorkbook workbook = null;
        try (InputStream inputStream = file.getInputStream()) {
            workbook = new XSSFWorkbook(inputStream);

            // 重复结算订单
            List<XsOrder> excel = new ArrayList<>();
            // 表存在数据
            List<XsOrder> exist = new ArrayList<>();
            // 表不存在数据
            List<XsOrder> nonentity = new ArrayList<>();
            // 查询全部订单
            List<XsOrder> xsOrderList = lambdaQuery().list();

            // 全部的订单id
            List<String> allId = new ArrayList<>();

            Map<String, String> map = new HashMap<>();
            xsStoreService.lambdaQuery().list().forEach(store -> {
                map.put(store.getStoreName(), store.getStoreCode());
            });

            /**
             * 去重用  根据 acookie_id service_code   pay_time不准，弃用
             */
            List<String> acookieIdList = new ArrayList<>();
            List<String> serviceCodeList = new ArrayList<>();

            // 遍历每个工作表
            for (int sheetIndex = 0; sheetIndex < workbook.getNumberOfSheets(); sheetIndex++) {
                Sheet sheet = workbook.getSheetAt(sheetIndex);
                String sheetName = sheet.getSheetName();

                String result = Pattern.compile("笔|墨").matcher(sheetName).find() ? "BM" : "HZG";

                // 数据列表
                List<XsOrderImportDto> importDtoList = util.importExcel(sheetName, file.getInputStream(), 0);

                if (StringUtils.isNotEmpty(importDtoList)) {
                    for (XsOrderImportDto importDto : importDtoList) {
                        orderId = importDto.getAcookieId();
                        XsOrder xsOrder = new XsOrder();
                        BeanUtil.copyProperties(importDto, xsOrder);
                        xsOrder.setWriterNickName(StringUtils.isNotEmpty(importDto.getWriter()) ? importDto.getWriter().trim() : importDto.getWriter());
                        xsOrder.setUpdateBy(SecurityUtils.getUsername());
                        xsOrder.setUpdateTime(DateUtils.getNowDate());

                        xsOrder.setPutPayment(new BigDecimal(importDto.getPutPayment()));
                        xsOrder.setClientPaidPrice(ObjectUtil.isNotEmpty(xsOrder.getClientPaidPrice()) ? xsOrder.getClientPaidPrice() : "0");
                        xsOrder.setWriterPaidPrice(ObjectUtil.isNotEmpty(xsOrder.getWriterPaidPrice()) ? xsOrder.getWriterPaidPrice() : "0");

                        if (StringUtils.isNotEmpty(map)) {
                            if (Pattern.compile("笔|墨").matcher(sheetName).find()) {
                                xsOrder.setStoreCode(map.get("笔墨画千秋"));
                            } else {
                                xsOrder.setStoreCode(map.get("回字格"));
                            }
                        }
                        // 订单来源
                        if (StringUtils.isEmpty(xsOrder.getAcookieId()) && StringUtils.isEmpty(xsOrder.getOrderSource())) {
                            xsOrder.setOrderSource(OrderSourceEnum.OFFLINE.getInfo());
                        }
                        // 是否刷单
                        xsOrder.setIfBrushing(StringUtils.isNotEmpty(xsOrder.getIfBrushing()) && xsOrder.getIfBrushing().contains("是") ? "1" : "2");

                        // 是否报账
                        xsOrder.setCheckSheet(StringUtils.isEmpty(importDto.getCheckSheet()) ? "2" : importDto.getCheckSheet().length() == 1 ? "1" : "2");
                        xsOrder.setOrderId(OrderNumberGenerator.generateOrderNumber(result.toUpperCase()));
                        xsOrder.setStatus("2");

                        // 订单状态
                        if (StringUtils.isNotEmpty(importDto.getStatus())) {
                            xsOrder.setStatus(importDto.getStatus());
                            if (xsOrder.getStatus().equals("2")) {
                                xsOrder.setCheckSheet("1");
                                xsOrder.setIfBalance("1");
                            } else if (xsOrder.getStatus().equals("3")) {
                                xsOrder.setCheckSheet("2");
                                xsOrder.setIfBalance("2");
                            } else if (xsOrder.getStatus().equals("4")) {
                                xsOrder.setCheckSheet("2");
                                xsOrder.setIfBalance("2");
                            } else {
                                BigDecimal refund = new BigDecimal(xsOrder.getRefund());
                                if (xsOrder.getPutPayment().doubleValue() == 0.0 && refund.doubleValue() < xsOrder.getActualPayment().doubleValue()) {
                                    xsOrder.setCheckSheet("1");
                                    xsOrder.setIfBalance("1");
                                }
                            }
                        }

                        if (StringUtils.isNotEmpty(importDto.getWriterPaidPrice())
                                && new BigDecimal(importDto.getWriterPaidPrice()).compareTo(BigDecimal.ZERO) > 0) {
                            xsOrder.setIfAudit("2");
                        }

                        // 判断总金额 是否一致
                        if (allId.contains(xsOrder.getAcookieId())) {
                            if (xsOrder.getPayment() != null && xsOrder.getPayment().compareTo(BigDecimal.ZERO) > 0) {
                                xsOrder.setPayment(BigDecimal.ZERO);
                            }
                        } else {
                            allId.add(xsOrder.getAcookieId());
                        }

                        // 判断系统已有订单
                        if (StringUtils.isNotEmpty(xsOrderList)) {
                            Set<String> orderIdSet = xsOrderList.stream().map(XsOrder::getAcookieId)
                                    .filter(id -> id != null && !id.isEmpty())
                                    .collect(Collectors.toSet());

                            if (orderIdSet.contains(xsOrder.getAcookieId())) {
                                // 使用Optional来处理可能的空值情况
                                Optional<XsOrder> existingOrderOpt = xsOrderList.stream()
                                        .filter(o -> Objects.equals(o.getAcookieId(), importDto.getAcookieId()))
                                        .findFirst();
                                if (existingOrderOpt.isPresent()) {
                                    // 数据库当前重复数据
                                    XsOrder existingOrder = existingOrderOpt.get();
                                    // 判断是否为 结单
                                    if ("6".equals(existingOrder.getStatus()) || "3".equals(existingOrder.getCheckSheet())) {
                                        xsOrder.setRepetitionCount(existingOrder.getRepetitionCount() + 1);
                                        excel.add(xsOrder);
                                    }
                                    xsOrder.setId(existingOrder.getId());
                                    xsOrder.setOrderId(existingOrder.getOrderId());
                                    xsOrder.setUpdateBy(SecurityUtils.getUsername());
                                    xsOrder.setUpdateTime(DateUtils.getNowDate());
                                    xsOrder.setModified(DateUtils.getNowDate());
                                    exist.add(xsOrder);
                                }
                            } else {
                                xsOrder.setCreateBy(SecurityUtils.getUsername());
                                xsOrder.setCreateTime(DateUtils.getNowDate());
                                //同一批导入去重
                                if(!acookieIdList.contains(xsOrder.getAcookieId()) && !serviceCodeList.contains(xsOrder.getServiceCode())){
                                    //不包含
                                    nonentity.add(xsOrder);
                                    acookieIdList.add(xsOrder.getAcookieId());
                                    serviceCodeList.add(xsOrder.getServiceCode());
                                }
                            }
                        } else {
                            xsOrder.setCreateBy(SecurityUtils.getUsername());
                            xsOrder.setCreateTime(DateUtils.getNowDate());
                            //同一批导入去重
                            if(!acookieIdList.contains(xsOrder.getAcookieId()) && !serviceCodeList.contains(xsOrder.getServiceCode())){
                                //不包含
                                nonentity.add(xsOrder);
                                acookieIdList.add(xsOrder.getAcookieId());
                                serviceCodeList.add(xsOrder.getServiceCode());
                            }
                        }
                        count++;
                    }
                }
            }

            this.updateOrder(exist);
            if (StringUtils.isNotEmpty(nonentity)) {
                this.saveBatch(nonentity);
            }
            // 重复结算
            if (CollectionUtil.isNotEmpty(excel)) {
                // 插入数据库
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new GlobalException("文件读取错误");
        } catch (Exception e) {
            throw new RuntimeException(e + "--" + count + "---" + orderId);
        } finally {
            try {
                workbook.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            //放单价=0并且退款金额<实收价=结算  统一处理订单状态
            log.debug("--------------------统一处理订单状态--------------------");
            this.update(new UpdateWrapper<XsOrder>().eq("put_payment","0.0").apply("refund < actual_payment").set("if_balance",1));
        }
    }
}




